// pages/search/search.js
import throttle from '../../utils/throttle.js';

const app = getApp();

// 是否正在修改input内的值
let changeInputValue = false;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        isFocus: true,
        isCancel: true,
        // 输入框内容
        inputValue: '',
        // 模糊匹配的城市
        matchCity: [],
        // 有匹配
        match: true,
        // 正在搜索
        searching: false,
    },
    // 返回上一页
    back() {
        wx.navigateBack({
            detal: 1,
        });
    },

    // 监听input输入
    bindKeyInput: throttle(function (e) {
        if (changeInputValue) return;
        this.setData(
            {
                inputValue: e.detail.value,
                matchCity: [],
            },
            () => {
                this.searchCities(e.detail.value);
            }
        );
    }, 1000),

    clear() {
        changeInputValue = true;
        this.setData({
            isCancel: true,
            inputValue: '',
        });
    },

    // focus事件
    focus() {
        changeInputValue = false;
        this.setData({
            isCancel: false,
            isFocus: true,
        });
    },

    blur() {
        this.setData({
            isFocus: false,
        });
    },
    // 搜索城市
    searchCities(inputValue) {
        if (!inputValue) return;
        this.setData({
            searching: true,
        });
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'code/searchCityOrUser',
            data: {
                content: inputValue,
            },
            success(res) {
                if (res.data.status === '0') {
                    let matchCity = res.data.data;
                    matchCity.forEach((item) => {
                        item.nodes = `<span>${item.city || item.name}<span>`;
                        item.foreignName =
                            item.enname &&
                            (item.enname.split(',')[2] ||
                                item.enname.split(',')[1]);
                    });

                    if (_that.isAllChinese(_that.data.inputValue)) {
                        _that.strongMatchWord(
                            matchCity,
                            'nodes',
                            _that.data.inputValue
                        );
                    }

                    _that.setData({
                        matchCity: matchCity,
                        match: matchCity.length > 0,
                        searching: false,
                    });
                }
            },
        });
    },

    goToIndex(e) {
        let _that = this;

        let country = e.currentTarget.dataset.country;
        let city = e.currentTarget.dataset.city;

        let lng = e.currentTarget.dataset.lng;
        let lat = e.currentTarget.dataset.lat;
        if (e.currentTarget.dataset.type == '01') {
            //typr   01---同事   00---城市
            wx.navigateTo({
                url: `../../functionPage/pages/othersHomePage/othersHomePage?uid=${e.currentTarget.dataset.uid}`,
            });
        } else {
            // 有些城市后台暂时没有经纬度
            if (lng && lat) {
                // 修改全局变量
                app.globalData.countryBack = country;
                app.globalData.addressBack = city;
                app.globalData.cityLat = lat;
                app.globalData.cityLng = lng;

                let pages = getCurrentPages(); //当前页面栈
                let prevPage = pages[pages.length - 2]; //上一页面
                prevPage.setData({
                    //直接给index页面赋值
                    mapLongitude: lng,
                    mapLatitude: lat,
                    mapScale: 12,
                });
                wx.navigateBack({
                    detal: 1,
                });
            } else {
                wx.showModal({
                    title: '位置获取失败',
                    content: '当前城市暂未覆盖，请联系后台管理员',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            _that.clear();
                        }
                    },
                });
            }
        }
    },

    // 判断是否全是汉字，只有全是汉字才高亮
    isAllChinese(str) {
        let reg = /^[\u4E00-\u9FA5]+$/;
        if (!reg.test(str)) {
            return false;
        } else {
            return true;
        }
    },

    // 高亮搜索的字段
    strongMatchWord(matchCity, key, inputValue) {
        let wordArr = inputValue.split('');
        for (let i = 0; i < matchCity.length; i++) {
            for (let j = 0; j < wordArr.length; j++) {
                let reg = new RegExp('(' + wordArr[j] + ')', 'g');
                matchCity[i][key] = matchCity[i][key].replace(
                    reg,
                    "<font style='color:#00c7ff;'>$1</font>"
                );
            }
        }
    },
});
